import pymysql


class DBTools:

    @classmethod
    def __create_conn(cls):
        conn = pymysql.connect(host='192.168.174.132',
                               port=3306,
                               user='root',
                               password='iTest_2022_mysql',
                               database='ihrm',
                               charset='utf8')
        return conn

    @classmethod
    def query_all(cls, sql):
        conn = None
        cursor = None
        resp = None
        try:
            conn = DBTools.__create_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            resp = cursor.fetchall()
        except Exception as err:
            print("执行 查询 SQL 失败：", err)
        finally:
            cursor.close()
            conn.close()
            return resp

    @classmethod
    def dml_sql(cls, sql):
        conn = None
        cursor = None
        try:
            conn = DBTools.__create_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()
            print("影响的行数:", conn.affected_rows())
        except Exception as err:
            print("执行 增删改 SQL 失败：", err)
            conn.rollback()
        finally:
            cursor.close()
            conn.close()


if __name__ == '__main__':
    select_sql = "select * from t_hero where gender = 1 order by gender asc;"
    # print(DBTools.query_all(select_sql))
    # ((1, '郭靖', 1, '降龙十八掌', 0, 1), (3, '乔峰', 1, '降龙十八掌', 0, 2), (4, '令狐冲', 1, '独孤九剑', 0, 3))
    for i in DBTools.query_all(select_sql):  # i是行记录
        print(i)
# (1, '郭靖', 1, '降龙十八掌', 0, 1)
# (3, '乔峰', 1, '降龙十八掌', 0, 2)
# (4, '令狐冲', 1, '独孤九剑', 0, 3)
